package starfield.ui;

import starfield.util.WindowsRegistry;
import java.awt.Toolkit;
import java.io.File;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import starfield.Application;
import starfield.Configuration;

public class PreferencesFrame extends javax.swing.JFrame {

    private boolean openMainFrameAfterClose;
    
    public PreferencesFrame(boolean openMainFrameAfterClose) {
        this.openMainFrameAfterClose = openMainFrameAfterClose;
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        applyButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        versionPresentationLabel = new javax.swing.JLabel();
        versionLabel = new javax.swing.JLabel();
        starboundPresentationLabel = new javax.swing.JLabel();
        pathField = new javax.swing.JTextField();
        browsePathButton = new javax.swing.JButton();
        webButton = new javax.swing.JButton();
        guessPathButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Starfield Preferences");
        setLocationByPlatform(true);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        applyButton.setText("OK");
        applyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.setDefaultCapable(false);
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        versionPresentationLabel.setText("Current version:");

        versionLabel.setText("[VERSION]");

        starboundPresentationLabel.setText("Starbound install path:");

        pathField.setText("[PATH]");

        browsePathButton.setText("...");
        browsePathButton.setDefaultCapable(false);
        browsePathButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browsePathButtonActionPerformed(evt);
            }
        });

        webButton.setText("Visit web page");
        webButton.setDefaultCapable(false);

        guessPathButton.setText("Try to guess path...");
        guessPathButton.setDefaultCapable(false);
        guessPathButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guessPathButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(applyButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(starboundPresentationLabel)
                            .addComponent(versionPresentationLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(versionLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(webButton))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(pathField)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(browsePathButton))
                            .addComponent(guessPathButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(10, 10, 10))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(versionPresentationLabel)
                    .addComponent(versionLabel)
                    .addComponent(webButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(starboundPresentationLabel)
                    .addComponent(pathField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browsePathButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(guessPathButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(applyButton))
                .addContainerGap())
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void guessPath() {
        String os = System.getProperty("os.name");
        String guessedPath = null;
        
        if (os.contains("Windows")) {
            try {
                String steamPath = WindowsRegistry.readString(WindowsRegistry.HKEY_CURRENT_USER, "Software\\Valve\\Steam", "SteamPath");
                guessedPath = steamPath + File.separator + "steamapps" + File.separator + "common" + File.separator + "Starbound";
            } catch (Exception ex) {
                
            }
        } else {
            
        }
        
        if (guessedPath != null) {
            pathField.setText(guessedPath);
            Toolkit.getDefaultToolkit().beep();
        } else {
            JOptionPane.showMessageDialog(this, Application.MSG_INSTALL_PATH_GUESS_FAIL, Application.TTL_INSTALL_PATH_GUESS, JOptionPane.WARNING_MESSAGE);
        }
    }
    
    private void applyAndClose() throws IOException{
		Configuration.setStarboundPath(pathField.getText());
		
        if (Configuration.isValid()) {
            Configuration.save();
			
			dispose();
			
            if (openMainFrameAfterClose) {
                MainFrame.launch();
            }
        } else {
			// TODO: Handle different invalid config params.
            JOptionPane.showMessageDialog(this, Application.MSG_INVALID_INSTALL_PATH, Application.TTL_INSTALL_PATH, JOptionPane.WARNING_MESSAGE);
        }
    }
    
    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
        versionLabel.setText(Application.VERSION);
		pathField.setText(Configuration.getStarboundPath());
    }//GEN-LAST:event_formWindowActivated

    private void guessPathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guessPathButtonActionPerformed
        guessPath();
    }//GEN-LAST:event_guessPathButtonActionPerformed

    private void applyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyButtonActionPerformed
        try {
		applyAndClose();
		} catch(Exception IOException){
			
		};
    }//GEN-LAST:event_applyButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void browsePathButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browsePathButtonActionPerformed
        JFileChooser j = new JFileChooser();
        j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        
        if (j.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            String path = j.getSelectedFile().getAbsolutePath();
            
            if (Configuration.isStarboundPathValid(path)) {
                pathField.setText(path);
            } else {
                JOptionPane.showMessageDialog(this, Application.MSG_INVALID_INSTALL_PATH, Application.TTL_INSTALL_PATH, JOptionPane.WARNING_MESSAGE);
            }
        }
    }//GEN-LAST:event_browsePathButtonActionPerformed

    public static void launch(final boolean openMainFrameAfterClose) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PreferencesFrame(openMainFrameAfterClose).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton applyButton;
    private javax.swing.JButton browsePathButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton guessPathButton;
    private javax.swing.JTextField pathField;
    private javax.swing.JLabel starboundPresentationLabel;
    private javax.swing.JLabel versionLabel;
    private javax.swing.JLabel versionPresentationLabel;
    private javax.swing.JButton webButton;
    // End of variables declaration//GEN-END:variables
}
